<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="预约id" prop="patientId">
        <el-input
          v-model="queryParams.patientId"
          placeholder="请输入预约id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出院状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择出院状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.patient_hospital_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['discharge:discharge:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['discharge:discharge:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="dischargeList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column
        label="预约状态"
        align="center"
        prop="register.registStatus"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.booking_status"
            :value="scope.row.register.registStatus"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="就诊卡号"
        align="center"
        prop="register.clinicCard"
      />
      <el-table-column label="预约姓名" align="center" prop="register.name" />
      <el-table-column label="性别" align="center" prop="register.sex">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_user_sex"
            :value="scope.row.register.sex"
          />
        </template>
      </el-table-column>

      <el-table-column label="年龄" align="center" prop="register.age" />
      <el-table-column label="手机号码" align="center" prop="register.phone" />
      <el-table-column
        label="预约科室"
        align="center"
        prop="register.departmentId"
      >
        <template slot-scope="scope">
          {{ deparvalue[scope.row.register.departmentId] }}
        </template>
      </el-table-column>
      <el-table-column label="预约医生" align="center" prop="register.doctorId">
        <template slot-scope="scope">
          {{ doctorvalue[scope.row.register.doctorId] }}
        </template>
      </el-table-column>
      <el-table-column
        label="预约渠道"
        align="center"
        prop="register.appointmentWay"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.user_channel_status"
            :value="scope.row.register.appointmentWay"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="挂号费用"
        align="center"
        prop="register.medicalFee"
      >
      </el-table-column>

      <el-table-column label="出院状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.patient_hospital_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column label="总费用(元)" align="center" prop="costTotal" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status == 0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['discharge:discharge:edit']"
            >开始随访</el-button
          >
          <el-button
            v-if="scope.row.status == 1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleOut(scope.row)"
            v-hasPermi="['discharge:discharge:remove']"
            >出院</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['discharge:discharge:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-claim"
            @click="handleTotal(scope.row)"
            v-hasPermi="['discharge:discharge:remove']"
            >消费单</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-data"
            @click="handleChart(scope.row)"
            v-hasPermi="['discharge:discharge:remove']"
            >图表</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改出院管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <div class="form-title">基本信息</div>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        class="custom-form"
      >
        <el-form-item label="患者姓名" prop="name">
          <el-input v-model="form.name" readonly />
        </el-form-item>
        <el-form-item label="就诊性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别" disabled>
            <el-option
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="门诊编号" prop="outpatientId">
          <el-input v-model="form.outpatientId" readonly />
        </el-form-item>
        <el-form-item label="身份证号" prop="identityCard">
          <el-input v-model="form.identityCard" readonly />
        </el-form-item>
        <el-form-item label="就诊年龄" prop="age">
          <el-input v-model="form.age" readonly />
        </el-form-item>
        <el-form-item label="医保性质" prop="nature">
          <el-select v-model="form.nature" disabled>
            <el-option
              v-for="dict in dict.type.patient_medical_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" readonly />
        </el-form-item>
        <el-form-item label="所属民族" prop="nation">
          <el-select v-model="form.nation" disabled>
            <el-option
              v-for="dict in dict.type.people_ethnic_ffiliation"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="住院编号" prop="admissionId">
          <el-input v-model="form.admissionId" readonly />
        </el-form-item>
      </el-form>

      <div class="form-title">随访信息</div>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        class="custom-form"
      >
        <el-form-item label="身体状态" prop="bodyStatus">
          <el-select v-model="form.bodyStatus" placeholder="请选择身体状态">
            <el-option
              v-for="dict in dict.type.patient_body_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计划时间" prop="planDate">
          <el-date-picker
            class="fixed-width-input"
            style="width: 160px"
            clearable
            v-model="form.planDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择计划随访日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="随访医生" prop="doctorId">
          <el-select v-model="currentDoctorId" placeholder="请选择医生">
            <el-option
              v-for="(doctorName, doctorId) in doctorvalue"
              :key="doctorId"
              :label="doctorName"
              :value="doctorId"
              disabled
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实际时间" prop="factDate">
          <el-date-picker
            class="fixed-width-input"
            style="width: 160px"
            clearable
            v-model="form.factDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择实际随访日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="随访记录" prop="remark">
          <el-input
            class="fixed-width-input"
            v-model="form.remark"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item label="随访记录" prop="pathogenRecord">
          <el-input
            class="fixed-width-input"
            v-model="form.pathogenRecord"
            placeholder="请输入随访记录"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
	  <el-form ref="form" :model="form" :rules="rules" label-width="80px">
	    <el-form-item label="出院状态" prop="status">
	      <el-radio-group v-model="form.status">
	        <el-radio
	          v-for="dict in dict.type.patient_hospital_status"
	          :key="dict.value"
	          :label="dict.value"
	        >{{dict.label}}</el-radio>
	      </el-radio-group>
	    </el-form-item>
	    <el-form-item label="总费用" prop="costTotal">
	      <el-input v-model="form.costTotal" placeholder="请输入总费用" />
	    </el-form-item>
	  </el-form>
	  <div slot="footer" class="dialog-footer">
	    <el-button type="primary" @click="submitForm">确 定</el-button>
	    <el-button @click="cancel">取 消</el-button>
	  </div>
	</el-dialog> -->

    <!-- 查看消费单对话框 -->
    <!-- Dialog -->
    <el-dialog title="消费单详情" :visible.sync="dialogVisible" width="50%">
      <div class="custom-descriptions-container">
        <div class="custom-descriptions-item">
          <span class="label">挂号费用：</span>
          <span class="value" v-if="totalForm.registerCost !== ''"
            >{{ costDetail[totalForm.registerCost] }}元</span
          >
          <span class="label" v-else>无</span>
        </div>
        <div class="custom-descriptions-item">
          <span class="label">问诊费用：</span>
          <span class="value" v-if="totalForm.interrogationCost !== ''"
            >{{ costDetail[totalForm.interrogationCost] }}元</span
          >
          <span class="label" v-else>无</span>
        </div>
        <div class="custom-descriptions-item">
          <span class="label">药品费用：</span>
          <span class="value" v-if="totalForm.medicalCost !== ''"
            >{{ costDetail[totalForm.medicalCost] }}元</span
          >
          <span class="label" v-else>无</span>
        </div>
        <div class="custom-descriptions-item">
          <span class="label">病房费用：</span>
          <span class="value" v-if="totalForm.wardCost !== ''"
            >{{ costDetail[totalForm.wardCost] }}元</span
          >
          <span class="label" v-else>无</span>
        </div>
        <div class="custom-descriptions-item">
          <span class="label">检查费用：</span>
          <span class="value" v-if="totalForm.inspectionCost !== ''"
            >{{ costDetail[totalForm.inspectionCost] }}元</span
          >
          <span class="label" v-else>无</span>
        </div>
        <div class="custom-descriptions-item">
          <span class="label">总费用：</span>
          <span class="value">{{ patientCurrentMoney }}元</span>
        </div>
        <!-- 其他费用项类似 -->
        <div>
          <el-button type="primary" @click="goPay" v-if="isPay == false"
            >去支付</el-button
          >
          <el-button type="success" v-else>已支付</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getInfo } from "@/api/login";
import { getYuyue } from "@/api/register/yuyue";
import {
  listFollowup,
  getFollowup,
  delFollowup,
  addFollowup,
  updateFollowup,
} from "@/api/followup/followup";
import {
  listDischarge,
  getDischarge,
  delDischarge,
  addDischarge,
  updateDischarge,
  getDoctorId,
} from "@/api/discharge/discharge";
import { listDepartment } from "@/api/department/department";
import { listDoctor } from "@/api/doctor/doctor";
import { listCost } from "@/api/cost/cost";
// 	引入支付
import { pay, ispay } from "@/api/discharge/pay";

export default {
  name: "Discharge",
  dicts: [
    "people_ethnic_ffiliation",
    "patient_hospital_status",
    "user_channel_status",
    "sys_user_sex",
    "booking_status",
    "patient_body_status",
    "patient_medical_status",
  ],
  data() {
    return {
      dialogVisible: false, //	控制消费单显示隐藏
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出院管理表格数据
      dischargeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        patientId: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 费用单
      totalForm: {
        registerCost: "",
        interrogationCost: "",
        medicalCost: "",
        wardCost: "",
        inspectionCost: "",
      },
      // 表单校验
      rules: {},
      deparvalue: {},
      doctorvalue: [],
      costDetail: [],
      patientCurrentId: "", //	当前消费单的患者id
      patientCurrentMoney: "", //	当前消费单的金额
      isPay: false, //	是否已付费

      currentDoctorId: "",
    };
  },
  created() {
    this.getUser();
    this.getList();
    this.getDepartmentList();
    this.getDoctorList();
    window.loca
  },
  methods: {
    //	点击打开图表	----	静态
    handleChart(row) {
      this.reset();
      this.$router.push({
        name: "discharge/discharge/echarts",
      });
    },

    //	获取当前登录用户为医生时的id
    getUser() {
      getInfo().then((res) => {
        console.log(res.user.userName);
        getDoctorId(res.user.userName).then((response) => {
          console.log(response);
          this.currentDoctorId = response.data;
        });
      });
    },
    //	去支付的方法
    goPay() {
      pay(this.patientCurrentId, this.patientCurrentMoney)
        .then((res) => {
          var payGatewayHtml = res; // 假设这是返回的HTML表单字符串

          // 创建一个新的窗口（或标签页）
          var newWindow = window.open("", "_blank");

          // 如果新窗口被阻止，则处理错误情况
          if (
            !newWindow ||
            newWindow.closed ||
            typeof newWindow.closed == "undefined"
          ) {
            alert("新窗口被阻止，请允许弹出窗口以继续支付。");
            return;
          }

          // 写入表单HTML到新窗口的文档中
          newWindow.document.write(payGatewayHtml);

          // 由于document.write是同步的，我们可以立即关闭写入流
          newWindow.document.close();

          // 注意：通常不需要手动提交表单，因为表单HTML可能已经包含了自动提交的逻辑（如onsubmit事件）
          // 如果需要手动提交，并且表单有唯一的ID或可以通过其他方式选择，你可以在新窗口的文档中查找并提交它
          // 例如：var form = newWindow.document.getElementById('paymentForm'); form.submit();
          // 但这通常不是必需的，除非支付网关有特定的要求
        })
        .catch((error) => {
          console.error("支付请求失败:", error);
        });
    },

    // goPay() {
    // 	pay(11).then(res => {
    // 		var payGateWay = res;
    // 		const div = document.createElement("div");
    // 		div.innerHTML = payGateWay; //此处form就是后台返回接收到的数据
    // 		document.body.appendChild(div);
    // 		document.forms[0].submit();
    // 	})
    // },

    //	出院
    handleOut(row) {
      row.status = 0;
      let id = row.id;
      let status = row.status;
      return updateDischarge({ id, status })
        .then((response) => {})
        .catch(() => {
          this.$modal.msgError("操作失败");
        });
    },
    // 查询科室列表
    getDepartmentList() {
      listDepartment().then((response) => {
        for (var i = 0; i < response.rows.length; i++) {
          this.$set(
            this.deparvalue,
            response.rows[i].id,
            response.rows[i].name
          );
        }
        // console.log(this.deparvalue);
      });
    },
    // 查询医生列表
    getDoctorList() {
      listDoctor().then((response) => {
        for (var i = 0; i < response.rows.length; i++) {
          this.$set(
            this.doctorvalue,
            response.rows[i].id,
            response.rows[i].name
          );
        }
        console.log(this.doctorvalue);
      });
    },

    /** 查询出院管理列表 */
    getList() {
      this.loading = true;
      listDischarge(this.queryParams).then((response) => {
        this.dischargeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        patientId: null,
        status: null,
        costTotal: null,
        del: null,
      };
      //	消费单重置
      this.totalForm = {
        registerCost: "",
        interrogationCost: "",
        medicalCost: "",
        wardCost: "",
        inspectionCost: "",
      };
      this.patientCurrentId = "";
      this.patientCurrentMoney = "";
      this.isPay = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加出院管理";
    },
    /** 随访按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getYuyue(row.patientId).then((response) => {
        this.form = response.data;
        this.form.patientId = response.data.id;
        console.log(this.form);
        this.open = true;
        this.title = "新增随访";
      });
    },
    // 消费单按钮操作
    handleTotal(row) {
      this.reset();
      this.loading = true;
      let query = {
        patientId: "",
      };
      //	获取当前患者id用作付费商品单号，金额用作转账额度
      query.patientId = row.patientId;
      this.patientCurrentId = row.patientId;
      this.patientCurrentMoney = row.costTotal;

      //	判断是否已经付过钱
      ispay(this.patientCurrentId).then((response) => {
        if (response == "10000") {
          console.log(response);
          this.isPay = true;
          console.log(this.isPay);
        } else {
          console.log("还没付过钱");
        }
      });

      listCost(query).then((response) => {
        // this.totalForm = response.rows
        // console.log(this.totalForm);
        for (var i = 0; i < response.rows.length; i++) {
          this.$set(
            this.costDetail,
            response.rows[i].costType,
            response.rows[i].money
          ); //	放入费用类型和金额到键值对数组中
          // console.log(response.rows[i].costType+":"+response.rows[i].money);
          if (response.rows[i].costType == "0") {
            this.totalForm.registerCost = response.rows[i].costType;
          } else if (response.rows[i].costType == "1") {
            this.totalForm.interrogationCost = response.rows[i].costType;
          } else if (response.rows[i].costType == "2") {
            this.totalForm.medicalCost = response.rows[i].costType;
          } else if (response.rows[i].costType == "3") {
            this.totalForm.wardCost = response.rows[i].costType;
          } else if (response.rows[i].costType == "4") {
            this.totalForm.inspectionCost = response.rows[i].costType;
          }
        }
        // console.log(this.costDetail);
      });
      this.loading = false;
      this.dialogVisible = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            console.log(this.form);
            addFollowup(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
            // updateDischarge(this.form).then(response => {
            //   this.$modal.msgSuccess("修改成功");
            //   this.open = false;
            //   this.getList();
            // });
          } else {
            addDischarge(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除出院管理编号为"' + ids + '"的数据项？')
        .then(function () {
          return delDischarge(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "discharge/discharge/export",
        {
          ...this.queryParams,
        },
        `discharge_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style>
.form-container {
  margin: 20px; /* 根据需要调整外边距 */
  padding: 20px; /* 根据需要调整内边距 */
  border: 1px solid #dcdcdc; /* 可选：添加边框 */
  border-radius: 4px; /* 可选：添加圆角 */
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1); /* 可选：添加阴影 */
}

.form-title {
  font-size: 14px; /* 根据需要调整字体大小 */
  font-weight: bold; /* 可选：加粗字体 */
  margin-bottom: 20px; /* 根据需要调整与表单之间的间距 */
}

.custom-form .el-form-item {
  flex: 1;
  min-width: 22%; /* 根据需要调整这个值，确保每行三个 */
  margin-right: 5%; /* 右侧间距，最后一个元素可以通过选择器去除 */
  box-sizing: border-box; /* 确保 padding 和 border 不会增加元素的总宽度 */
  /* 其他可能的样式，如 padding、border 等 */
}

.custom-form .el-form-item:nth-child(3n) {
  margin-right: 0; /* 去除每行最后一个元素的右侧间距 */
}

.custom-form {
  display: flex;
  flex-wrap: wrap; /* 允许子元素换行 */
  /* 根据需要调整其他样式，如宽度、高度等 */
}
.custom-descriptions-container {
  display: flex;
  flex-direction: column; /* 垂直布局 */
  align-items: stretch; /* 确保子项填满容器 */
}

.custom-descriptions-item {
  display: flex;
  justify-content: space-between; /* 水平对齐，两端对齐 */
  padding: 15px 0; /* 上下内边距 */
  border-bottom: 1px solid #ebeef5; /* 可选，添加分隔线 */
}

.custom-descriptions-item:last-child {
  border-bottom: none; /* 移除最后一个子项的分隔线 */
}

.label {
  flex: 1; /* 占据剩余空间的一部分 */
  font-weight: bold; /* 加粗 */
  margin-right: 20px; /* 与值之间添加间距 */
}

.value {
  flex: 2; /* 占据剩余空间的大部分 */
  font-size: 16px; /* 调整字体大小 */
}
</style>
